package com.tanhua.dubbo.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.dubbo.enums.CommentType;
import com.tanhua.dubbo.enums.IdType;
import com.tanhua.dubbo.pojo.Comment;
import com.tanhua.dubbo.pojo.UserFocus;
import com.tanhua.dubbo.pojo.Video;
import com.tanhua.dubbo.service.IdService;
import com.tanhua.dubbo.vo.PageInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.ArrayList;
import java.util.List;

@DubboService(version = "1.0.0")
public class VideoApiImpl implements VideoApi {

    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIEK_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    private String getCommentRedisKey(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    private String getCommentUserLikeRedisKey(Long userId) {
        return COMMENT_USER_LIEK_REDIS_KEY_PREFIX + userId;
    }

    private String getCommentUserLoveRedisKey(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 保存小视频
     *
     * @param video
     * @return 保存成功后，返回视频id
     */
    @Override
    public String saveVideo(Video video) {
        //校验
        if (!ObjectUtil.isAllNotEmpty(video.getUserId(),
                video.getPicUrl(), video.getVideoUrl())) {
            return null;
        }

        video.setId(ObjectId.get());
        video.setCreated(System.currentTimeMillis());
        video.setVid(this.idService.createId(IdType.VIDEO));
        video.setSeeType(1);

        this.mongoTemplate.save(video);

        return video.getId().toHexString();
    }

    /**
     * 查询小视频列表
     * 实现：优先查询推荐的小视频列表的数据，其次按照时间倒序排序查询MongoDB中的数据
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Video> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(new ArrayList<>());

        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
        String redisValue = this.redisTemplate.opsForValue().get(redisKey);
        List<String> vidStrList = StrUtil.split(redisValue, ',');
        List<Long> vidList = new ArrayList<>();
        if (CollUtil.isNotEmpty(vidStrList)) {
            //手动分页
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
            int start = startEnd[0]; //开始下标
            int end = Math.min(vidStrList.size(), startEnd[1]); // 结束下标

            for (int i = start; i < end; i++) {
                vidList.add(Convert.toLong(vidStrList.get(i)));
            }
        }

        if (CollUtil.isEmpty(vidList)) {
            //TODO 排除已经在推荐列表中返回的视频数据
            //没有推荐数据 或 推荐数据已经查完了
            //计算前面推荐数据的页数
            int totalPage = PageUtil.totalPage(vidStrList.size(), pageSize);

            PageRequest pageRequest = PageRequest.of(page - totalPage - 1, pageSize,
                    Sort.by(Sort.Order.desc("created")));
            Query query = Query.query(Criteria.where("vid").nin(vidStrList)).with(pageRequest);
            List<Video> videoList = this.mongoTemplate.find(query, Video.class);
            pageInfo.setRecords(videoList);
        } else {
            Query query = Query.query(Criteria.where("vid").in(vidList));
            List<Video> videoList = this.mongoTemplate.find(query, Video.class);

            //按照推荐顺序进行排序
            for (Long vid : vidList) {
                for (Video video : videoList) {
                    if (ObjectUtil.equal(vid, video.getVid())) {
                        pageInfo.getRecords().add(video);
                        break;
                    }
                }
            }
        }

        return pageInfo;
    }

    @Override
    public Video queryVideoById(String videoId) {
        return this.mongoTemplate.findById(new ObjectId(videoId), Video.class);
    }

    @Override
    public Integer queryCommentCount(ObjectId videoId) {
        Query query = Query.query(Criteria.where("publishId").is(videoId)
                .and("commentType").is(CommentType.COMMENT.getType()));
        List<Comment> comments = this.mongoTemplate.find(query, Comment.class);

        return comments.size();
    }

    @Override
    public Long queryLikeCount(String videoId) {
        String redisKey = this.getCommentRedisKey(videoId);
        String hashKey = CommentType.LIKE.name();
        return Convert.toLong(this.redisTemplate.opsForHash().get(redisKey, hashKey), 0L);
    }

    @Override
    public Boolean userFocus(String userId, String focusId) {
        try {
            UserFocus userFocus = new UserFocus();
            userFocus.setUserId(Convert.toLong(userId));
            userFocus.setLikeUserId(Convert.toLong(focusId));
            userFocus.setId(ObjectId.get());
            userFocus.setCreated(System.currentTimeMillis());

            this.mongoTemplate.save(userFocus);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Object userUnFocus(String userId, String uid) {
        Query query = Query.query(Criteria.where("userId").is(Convert.toLong(userId))
                .and("likeUserId").is(Convert.toLong(uid)));
        this.mongoTemplate.remove(query, UserFocus.class);
        return null;
    }

    @Override
    public Boolean queryUserIsLike(Long userId, String videoId) {
        String redisKey = this.getCommentRedisKey(videoId);
        String hashKey = this.getCommentUserLikeRedisKey(userId);
        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }

    @Override
    public Boolean queryUserIsFocus(Long userId, Long likeUserId) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("likeUserId").is(likeUserId));
        UserFocus userFocus = this.mongoTemplate.findOne(query, UserFocus.class);
        if(ObjectUtil.isEmpty(userFocus)) {
            return false;
        }
        return true;
    }
}
